/*
 * Created on Feb 11, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.query.project;

import java.util.Set;

import com.hp.hpl.jena.rdf.model.Model;

import edu.mit.simile.longwell.Cache;
import edu.mit.simile.longwell.Profile;
import edu.mit.simile.longwell.ProfileListenerBase;

/**
 * @author dfhuynh
 */
public abstract class ProjectorBase extends ProfileListenerBase implements IProjector {
	final protected Profile m_profile;
	final protected Cache	m_resultCache = new Cache(10, ProjectorBase.class, "results");

	final static protected Cache s_rootProjections = new Cache(10, ProjectorBase.class, "root-projections");
	
	protected ProjectorBase(Profile profile) {
		m_profile = profile;
	}
	
	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.query.project.IProjector#project()
	 */
	public IProjection project() {
		IProjection projection = (IProjection) s_rootProjections.get(this);
		if (projection == null) {
			projection = internalProject();
			
			s_rootProjections.put(this, projection);
		}
		return projection;
	}
	
	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.query.IProjector#project(java.util.Set)
	 */
	public IProjection project(Set objects) {
		IProjection projection = (IProjection) m_resultCache.get(objects);
		if (projection == null) {
			projection = internalProject(objects);
			
			m_resultCache.put(objects, projection);
		}
		return projection;
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.longwell.ProfileListenerBase#onAfterChange(com.hp.hpl.jena.rdf.model.Model)
	 */
	protected void onAfterChange(Model model) {
		// Very crude refreshing strategy
		m_resultCache.clear();
		s_rootProjections.remove(this);
	}

	abstract protected IProjection internalProject();

	abstract protected IProjection internalProject(Set objects);
}
